package ch5;

import util.Debug;
import util.Tools;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用条件变量实现等待超时控制
 */

public class TimeoutWaitWithCondition {
    private static final Lock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();
    private static boolean ready = false;
    protected static final Random random = new Random();

    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread() {
            @Override
            public void run() {
               for (;;) {
                   lock.lock();
                   try {
                       ready = random.nextInt(100) < 30 ? true : false;
                       if (ready) {
                           condition.signal();
                       }
                   } finally {
                       lock.unlock();
                   }

                   // 使当前线程暂停一段随机时间
                   Tools.randomPause(500);
               }
            }
        };
        t.setDaemon(true);
        t.start();
        waiter(1000);
    }

    public static void waiter(final long timeout) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException();
        }
        // 计算等待的最后期限
        final Date deadLine = new Date(System.currentTimeMillis() + timeout);

        // 是否继续等待的标志
        boolean continueToWait = true;
        lock.lock();
        try {
            while (!ready) {
                Debug.info("still not ready, continue to wait: %s", continueToWait);
                // 等待未超时，继续等待
                if (!continueToWait) {
                    // 等待超时退出
                    Debug.error("Wait timed out, unable to execution target action!");
                    return;
                }
                // 如果等待超时，则返回false
                // 否则，如果是等待变量执行了signal，则返回true
                continueToWait = condition.awaitUntil(deadLine);
            }

            // 执行目标动作
            guardedAction();
        } finally {
            lock.unlock();
        }
    }

    private static void guardedAction() {
        Debug.info("Take some action.");
    }
}
